package com.dataart.productshop.controller;

import com.dataart.productshop.Constants;
import com.dataart.productshop.file.utils.StringUtils;
import com.dataart.productshop.model.boiko.informationsystem.Subject;
import com.dataart.productshop.service.SubjectManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AddSubjectController {

    @Autowired
    SubjectManager subjectManager;

    @RequestMapping(value = "/addSubject", method = RequestMethod.GET)
    public ModelAndView createSubjectGet(){
        return standartSbjPage();
    }

    @RequestMapping(value = "/addSubject", method = RequestMethod.POST)
    public ModelAndView createSubjectPost(@RequestParam(Constants.NEW_ELEMENT_NAME) String subjectName){
        if(!StringUtils.isEmpty(subjectName)){
            Subject sbj = new Subject();
            sbj.setName(subjectName);
            subjectManager.save(sbj);
        }

        return standartSbjPage();
    }

    @RequestMapping(value = "/remove" + Constants.SUBJECT_TYPE + "/{itemId}"
            , method = RequestMethod.GET)
    public String removeSubject(@PathVariable("itemId") String itemId){
        try{
            subjectManager.delete(Long.parseLong(itemId));
        }catch (NumberFormatException e){

        }catch(Exception dd){
            System.err.println("some exception were occured in AssKathedra controller"
                    + dd.getStackTrace());
        }
        return "redirect:/addSubject";
    }

    @RequestMapping(value = "/edit" + Constants.SUBJECT_TYPE + "/{itemId}"
            , method = RequestMethod.GET)
    public String editSubject(@PathVariable("itemId") String itemId){
        try{
            subjectManager.delete(Long.parseLong(itemId));
        }catch (NumberFormatException e){

        }catch(Exception dd){
            System.err.println("some exception were occured in AssKathedra controller"
                    + dd.getStackTrace());
        }
        return "redirect:/addSubject";
    }



    private ModelAndView standartSbjPage(){
        Map<String, Object> viewElements= new HashMap<String, Object>();
        viewElements.put(Constants.KATHEDRA_N_SUBJECT_LIST_NAME, subjectManager.getAll());
        viewElements.put(Constants.KATHEDRA_N_SUBJECT_CURRENT_TYPE, Constants.SUBJECT_TYPE);
        viewElements.put(Constants.NEW_ELEMENT_NAME, Constants.NEW_ELEMENT_NAME);
        return new ModelAndView("addSubjectOrKathedra", viewElements);
    }
}
